package com.xinyue.auto;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import com.xinyue.auto.bean.Entity;
import com.xinyue.auto.sql.MySqlDB;
import com.xinyue.auto.sql.SqlContext;

/**
 * 创建sql语句
 */
public class SqlBuilder {
	private String sqlFolder;
	
	public SqlBuilder(String sqlFolder) {
		this.sqlFolder = sqlFolder;
	}
	
	/**
	 * @param entites
	 * @throws IOException
	 */
	public void crateSql(List<Entity> entites) throws IOException {
		//mysql数据流
		PrintWriter mySqlWriter = getPrintWriter("/mySql.sql");
		
		SqlContext mysql = new MySqlDB();
		//读写数据
		for (Entity entity: entites) {
			mysql.createSql(entity, mySqlWriter);
		}
		
		//关闭流
		closeWriter(mySqlWriter);
	}
	
	
	/**
	 * 清空文件并创建文件流
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private PrintWriter getPrintWriter(String fileName) throws IOException {
		File file = new File(sqlFolder + fileName);
		if(file.exists()) {
			file.delete();
		}else {
			file.getParentFile().mkdirs();
		}
		
		file.createNewFile();
		PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
		
		return pw;
	}
	
	/**
	 * 缓存内容写入文件并关闭流
	 */
	private void closeWriter(PrintWriter pw) {
		pw.flush();
		pw.close();
	}
}